package com.xunk.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.xunk.common.core.utils.XunkAssert;
import com.xunk.common.core.utils.poi.ExcelUtil;
import com.xunk.common.core.web.controller.BaseController;
import com.xunk.common.core.web.domain.AjaxResult;
import com.xunk.common.core.web.page.TableDataInfo;
import com.xunk.common.log.annotation.Log;
import com.xunk.common.log.enums.BusinessType;
import com.xunk.common.security.utils.SecurityUtils;
import com.xunk.system.api.domain.SysHome;
import com.xunk.system.domain.SysHomeResponse;
import com.xunk.system.service.ISysHomeService;
import com.xunk.system.vo.AllotMasterVO;
import com.xunk.system.vo.MasterBindHomeRequestVO;
import com.xunk.system.vo.UserHomeInfoResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 家庭房屋信息Controller
 *
 * @author ruoyi
 * @date 2021-03-10
 */
@RestController
@RequestMapping("/home")
public class SysHomeController extends BaseController {

    @Autowired
    private ISysHomeService sysHomeService;

    /**
     * 查询家庭房屋信息列表
     */
    @PreAuthorize("@ss.hasPermi('buz:home:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysHome sysHome) {
        startPage();
        List<SysHomeResponse> list = sysHomeService.selectSysHomeList(sysHome);
        return getDataTable(list);
    }

    /**
     * 导出家庭房屋信息列表
     */
    @PreAuthorize("@ss.hasPermi('buz:home:export')")
    @Log(title = "家庭房屋信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysHome sysHome) throws IOException {
        List<SysHomeResponse> list = sysHomeService.selectSysHomeList(sysHome);
        ExcelUtil<SysHomeResponse> util = new ExcelUtil<>(SysHomeResponse.class);
        util.exportExcel(response, list, "home");
    }

    /**
     * 获取家庭房屋信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('buz:home:query')")
    @GetMapping(value = "/{homeId}")
    public AjaxResult getInfo(@PathVariable("homeId") Long homeId) {
        return AjaxResult.success(sysHomeService.selectSysHomeById(homeId));
    }

    /**
     * 新增家庭房屋信息
     */
    @PreAuthorize("@ss.hasPermi('buz:home:add')")
    @Log(title = "家庭房屋信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysHome sysHome) {
        return toAjax(sysHomeService.insertSysHome(sysHome));
    }

    /**
     * 修改家庭房屋信息
     */
    @PreAuthorize("@ss.hasPermi('buz:home:edit')")
    @Log(title = "家庭房屋信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysHome sysHome) {
        return toAjax(sysHomeService.updateSysHome(sysHome));
    }

    /**
     * 删除家庭房屋信息
     */
    @PreAuthorize("@ss.hasPermi('buz:home:remove')")
    @Log(title = "家庭房屋信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{homeIds}")
    public AjaxResult remove(@PathVariable Long[] homeIds) {
        return toAjax(sysHomeService.deleteSysHomeByIds(homeIds));
    }

//    @PreAuthorize("@ss.hasPermi('buz:home:member')")
    @GetMapping("/member/{homeId}")
    public AjaxResult getHomeMember(@PathVariable Long homeId) {
        return AjaxResult.success(sysHomeService.selectHomeMemberByHomeId(homeId));
    }

    /**
     * 屋主绑定房屋信息，通过房屋的邀请码绑定，而且邀请码只能使用一次
     *
     * @param requestVO
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('buz:home:bind')")
    @PostMapping("/master/bind")
    public AjaxResult masterBindHome(@RequestBody MasterBindHomeRequestVO requestVO) {
        XunkAssert.notEmpty(requestVO.getInviteCode(), "邀请码不能为空");
        sysHomeService.masterBindHome(requestVO);
        return AjaxResult.success();
    }

    /**
     * 普通用户通过二维码绑定房屋信息
     *
     * @return 结果
     */
//    @PreAuthorize("@ss.hasPermi('buz:home:bind')")
    @Log(title = "用户绑定房屋", businessType = BusinessType.OTHER)
    @PostMapping("/user/bind")
    public AjaxResult UserBindHome(@RequestBody String params) {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        String qrCode = paramsJSONObject.getString("qrCode");
        sysHomeService.userBindHome(qrCode);
        return AjaxResult.success();
    }

    /**
     * 房屋主人将某成员移除出该家庭
     *
     * @return 结果
     */
//    @PreAuthorize("@ss.hasPermi('buz:home:remove')")
    @Log(title = "删除家庭成员", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public AjaxResult removeUserFromHome(@RequestBody Map<String,Long> params) {

        Long homeId = params.get("homeId");
        Long userId = params.get(("userId"));
        sysHomeService.removeUserFromHome(userId, homeId);
        return AjaxResult.success();
    }

    /**
     *  非房主用户退出家庭
     *      房主不能退出自己的家庭
     *
     * @param params    家庭id
     * @return
     */
    @PostMapping("/quit")
    public AjaxResult quitHome(@RequestBody String params) {
        JSONObject paramsJSONObject = JSONObject.parseObject(params);
        Long homeId = paramsJSONObject.getLong("homeId");
        sysHomeService.quitHome(homeId);
        return AjaxResult.success();
    }

    /**
     * 户主让位给指定用户
     *
     * @return 结果
     */
//    @PreAuthorize("@ss.hasPermi('buz:home:allot')")
    @Log(title = "户主让位", businessType = BusinessType.UPDATE)
    @PutMapping("/allot")
    public AjaxResult allotMaster(@RequestBody AllotMasterVO masterVO, @RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authHeader) {
        sysHomeService.allotMasterToUser(masterVO,authHeader);
        return AjaxResult.success();
    }

//    @PreAuthorize("@ss.hasPermi('buz:home:getHomeInfo')")
    @GetMapping("/getHomeInfo")
    public AjaxResult findHome() {
        Long userId = SecurityUtils.getUserId();
        UserHomeInfoResponseVO homeInfoResponseVO = sysHomeService.findHomeByUserId(userId);
        return AjaxResult.success(homeInfoResponseVO);
    }

    @GetMapping("/qr-code")
    public AjaxResult getMasterHomeInfo(String qrCode){
        return sysHomeService.selectMasterAndHomeInfo(qrCode);
    }

    @Log(title = "家庭房屋信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult editConsumeHome(@RequestBody SysHome sysHome) {
        return toAjax(sysHomeService.updateSysHome(sysHome));
    }
}
